package cn.wdm.ymcc.rocketmq.transactionlistenner;


import cn.wdm.ymcc.domain.PayOrder;
import cn.wdm.ymcc.dto.PayNotifyDto;
import cn.wdm.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQTransactionListener(
        txProducerGroup = "asynNotifyTransaction"//监听哪一种事务消息组,与发送消息事务消息组别名
)
public class AsynNotifyRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;
    /**
     * 执行本地事务
     * @param message 往mq存放的数据，拿去给消费者消费 PayNotifyDto
     * @param arg 额外的参数 payOrder
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        PayOrder payOrder = (PayOrder) arg;
        PayOrder payOrderTem = payOrderService.selectByOrderNo(payOrder.getOrderNo());
        if(payOrderTem.getPayStatus() != PayOrder.STATE_WAIT_PAY){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        payOrderService.updateById(payOrder);
        return RocketMQLocalTransactionState.COMMIT;//执行本地事务成功
    }
    /**
     * 检查本地事务
     * @param message payNotifyDto
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] bodyTmp = (byte[]) message.getPayload();
            String notifyDtoStr = new String(bodyTmp, StandardCharsets.UTF_8);
            PayNotifyDto dto = JSONObject.parseObject(notifyDtoStr, PayNotifyDto.class);
            if(dto != null){
                return RocketMQLocalTransactionState.UNKNOWN;//未知
            }
            PayOrder orderTmp = payOrderService.selectByOrderNo(dto.getOrderNo());
            if(orderTmp == null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            //判断支付单的状态是否是已支付
            if(orderTmp.getPayStatus() == PayOrder.STATE_PAY_SUCCESS){
                return RocketMQLocalTransactionState.COMMIT;//才真正的发送事务消息成功
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

}
